#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<string>
#include<queue>
#include<unordered_map>

using namespace std;

int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };

int bfs(string& start)
{
    string end = "12345678x";
    queue<string> q;
    unordered_map<string, int> d;

    q.push(start);
    d[start] = 0;
    while (!q.empty())
    {
        string t = q.front();
        q.pop();
        int distance = d[t];
        if (t == end)    return distance;

        int k = t.find('x');
        int x = k / 3, y = k % 3;
        for (int i = 0; i < 4; i++)
        {
            int a = dx[i] + x;
            int b = dy[i] + y;
            if (a >= 0 && b >= 0 && a < 3 && b < 3)
            {
                swap(t[k], t[a * 3 + b]);
                if (!d.count(t))
                {
                    d[t] = distance + 1;
                    q.push(t);
                }
                swap(t[k], t[a * 3 + b]);
            }
        }
    }
    return -1;
}


int main()
{
    string start;
    for (int i = 0; i < 9; i++)
    {
        char c;
        cin >> c;
        start += c;
    }

    cout << bfs(start) << endl;
    return 0;
}